package com.shen.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shen.edu.entity.Chapter;
import com.shen.edu.entity.Video;
import com.shen.edu.entity.chapter.ChapterVo;
import com.shen.edu.entity.chapter.VideoVo;
import com.shen.edu.mapper.ChapterMapper;
import com.shen.edu.service.ChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shen.edu.service.VideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author shen
 * @since 2020-06-21
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Autowired
    private VideoService videoService;

    /**
     * 课程大纲列表，根据课程Id进行查询
     * @param courseId
     * @return
     */
    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {
        //1、根据课程Id查询课程里面所有的章节
        QueryWrapper<Chapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        List<Chapter> chapterList = baseMapper.selectList(wrapper);
        //2、根据课程Id查询课程里面所有的小节
        QueryWrapper<Video> wrapperVideo = new QueryWrapper<>();
        wrapperVideo.eq("course_id",courseId);
        List<Video> videoList = videoService.list(wrapperVideo);
        //创建list集合，用于最终封装数据
        List<ChapterVo> finalList = new ArrayList<>();

        //3、便利查询章节list集合进行封装
        //遍历查询章节list集合
        for (int i = 0; i < chapterList.size(); i++) {
            Chapter chapter = chapterList.get(i);
            //chapter对象值复制到ChapterVo
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter,chapterVo);
            //把ChapterVo放到最终List集合
            finalList.add(chapterVo);

            //创建集合，用于封装章节的小节
            List<VideoVo> videoVoList = new ArrayList<>();
            //4、遍历查询小节list集合，进行封装
            for (int j = 0; j < videoList.size(); j++) {
                Video video = videoList.get(j);
                //判断小节里面的chapter和章节里面的id是否一样
                if (video.getChapterId().equals(chapter.getId())){
                    //进行封装
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video,videoVo);
                    videoVoList.add(videoVo);
                }
            }
            chapterVo.setChildren(videoVoList);
        }
        return finalList;
    }
}
